package com.docking.heylo.service.impl;

import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.ApertureSerach;
import com.docking.heylo.dao.entity.Post;
import com.docking.heylo.dao.entity.UserApertureSet;
import com.docking.heylo.dao.mapper.ApertureSerachMapper;
import com.docking.heylo.dao.mapper.UserApertureSetMapper;
import com.docking.heylo.pojo.Aperture;
import com.docking.heylo.service.IApertureSearchService;
import com.docking.heylo.service.ICacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@Service
public class ApertureSearchServiceImpl implements IApertureSearchService {

    @Resource
    private ApertureSerachMapper apertureSerachMapper;

    @Resource
    private UserApertureSetMapper userApertureSetMapper;

    @Autowired
    private ICacheService cacheService;


    @Override
    public void index(Post post) {
        ApertureSerach search = apertureSerachMapper.selectByPrimaryKey(post.getUserId());
        if(search == null){
            apertureSerachMapper.insertSelective(new ApertureSerach(){{
                setUserId(post.getUserId());
                setReleaseTime(post.getCrtAt());
                setPostId(post.getId());
                setLat(post.getLat());
                setLon(post.getLon());
                setProfession(ThreadContext.type());
                setBigA(ThreadContext.bigA() ? (byte)1 : (byte)0);
                setSex(ThreadContext.authorize.get().getUser().getSex());
            }});
        }else{
            apertureSerachMapper.updateByPrimaryKeySelective(new ApertureSerach(){{
                setUserId(post.getUserId());
                setReleaseTime(post.getCrtAt());
                setPostId(post.getId());
                setLat(post.getLat());
                setLon(post.getLon());
                setBigA(ThreadContext.bigA() ? (byte)1 : (byte)0);
            }});
        }
    }


    @Override
    public List<Aperture> apertures() {
        UserApertureSet set = userApertureSetMapper.selectByPrimaryKey(ThreadContext.userId());
        List<Integer> userIdList = apertureSerachMapper.selectBySet(set, ThreadContext.userId(),
                ThreadContext.authorize.get().getLat(), ThreadContext.authorize.get().getLon());

        List<Aperture> apertures = new ArrayList<>(userIdList.size());
        for(Integer userId : userIdList){
            apertures.add(cacheService.getAperture(userId));
        }

        // 插入大A的作品



        return apertures;
    }







}
